package org.keshe.controllers;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import org.keshe.CurrentUser;
import org.keshe.data.BedDataWithButton;
import org.keshe.data.StuData;
import org.keshe.data.StuDataWithButton;
import org.keshe.user.AdminUser;

import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle;

public class OutStu implements Initializable {
    private AdminUser adminUser;

    @FXML
    private TableView<StuDataWithButton> table;
    @FXML
    private TableColumn<StuDataWithButton, String> s_id;
    @FXML
    private TableColumn<StuDataWithButton, String> sname;

    @FXML
    private TableColumn<StuDataWithButton, String> sex;

    @FXML
    private TableColumn<StuDataWithButton, String> major;

    @FXML
    private TableColumn<StuDataWithButton, String> bedName;

    @FXML
    private TableColumn<StuDataWithButton, Button> buttonCol;

    @FXML
    void refreshClick() {
        try {
            List<StuData> checkInStuData = adminUser.getCheckInStuData();
            loadTableContent(checkInStuData);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private void loadTableContent (List<StuData> list){
        ObservableList<StuDataWithButton> observableList = FXCollections.observableArrayList();
        for(StuData stuData : list){
            observableList.add(new StuDataWithButton(stuData));
        }
        table.setItems(observableList);
        for(StuDataWithButton stuDataWithButton : table.getItems()){
            stuDataWithButton.getDel().setText("退宿");
            stuDataWithButton.getDel().setOnAction(e -> {
                try {
                    adminUser.checkOutStu(stuDataWithButton.getS_id());
                    table.getItems().remove(stuDataWithButton);
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            });
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        if(CurrentUser.USER instanceof AdminUser){
            adminUser = (AdminUser) CurrentUser.USER;
        }else{
            throw new RuntimeException();
        }
        s_id.setCellValueFactory(new PropertyValueFactory<>("s_id"));
        sname.setCellValueFactory(new PropertyValueFactory<>("sname"));
        sex.setCellValueFactory(new PropertyValueFactory<>("sex"));
        major.setCellValueFactory(new PropertyValueFactory<>("major"));
        bedName.setCellValueFactory(new PropertyValueFactory<>("bedName"));
        buttonCol.setCellValueFactory(new PropertyValueFactory<>("del"));
    }
}
